﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;

using RRRSRoguelike.Enums;
using RRRSRoguelike.Helpers.Visualizer;
using RRRSRoguelike.Managers;
using RRRSRoguelikeData;
using RRRSRoguelike.Helpers.Webservice;

namespace RRRSRoguelike.Screens
{
	/// <summary>
	/// Manages the UI to prompt user for high score service.
	/// </summary>
	class HighScoreScreen : Screen
	{
        HighScoreAPI hs = new HighScoreAPI();

		public HighScoreScreen()
		{
			PanelList.Add(new Panel(new Point(4, 3),
					Visualizer.GetScreenWidth() - 9, Visualizer.GetScreenHeight() - 6));
		}

		public override void Show()
		{
			Clear();

			foreach (Panel p in PanelList)
			{
				p.Clear();
				p.Draw();
			}

				//Temp place holder for score, need to set this to actual score value
				string name = ApplicationManager.Instance.Profile.Name;
						
				PanelList[0].Clear();
				
				Session session = ApplicationManager.Instance.Profile.Session;

				string[] names = Enum.GetNames(typeof(HighScoreEntries));
				
				int[] colWidths = new int[names.Length];
				for (int i = 0; i < names.Length;i++)
				{
					//colWidths[i] = names[i].Length + 2;
					colWidths[i] = 17;
				}
				colWidths[(int)HighScoreEntries.Name] = 17;
				//HACK: We should limit ruleset names to 15chars
				colWidths[(int)HighScoreEntries.Ruleset] = 17;
				
				ApplicationManager.Instance.Profile.HighScores.Entries.Add((HighScoreEntry)session.tempScore.Clone());
				
				ApplicationManager.Instance.Profile.HighScores.Entries.Sort(
						    
					delegate(HighScoreEntry s1, HighScoreEntry s2)
					{
						int compareEntry = int.Parse(s2.Data["Score"]).CompareTo(int.Parse(s1.Data["Score"]));
					
						return compareEntry;
					}
				);
				
				//headings
				PanelList[0].Write(Visualizer.PrepareRow(
					names,
					colWidths),0);
				
				int maxEntries = Math.Min(ApplicationManager.Instance.Profile.HighScores.Entries.Count,10);
				//scores
				for(int i = 0; i< maxEntries;i++)
				{
					List<string> tempList = ApplicationManager.Instance.Profile.HighScores.Entries[i].Data.Values.ToList<string>();
					
					//Highlight recent score
					ConsoleColor cc = ConsoleColor.White;
					if (tempList[0] == ApplicationManager.Instance.Profile.Session.tempScore.Data["ID"])
						cc = ConsoleColor.Cyan;
					
					//remove ID
					tempList.RemoveAt(0);
					
					
					string[] values = (string[])tempList.ToArray();
						PanelList[0].Write(Visualizer.PrepareRow(values,
							colWidths),1+i, cc);
				}
				
				ApplicationManager.Instance.Profile.Save();
				
				WaitKey();

                //prompt user
                PanelList[0].Write(Properties.Strings.HighScore + Properties.Strings.YNQuestion);

                //temp placeholder for unique ID to so only game can update webservice
                string guid = "guid94723";
                bool submitScore;
                ConsoleKey answer;

                //read keyboard
                answer = Console.ReadKey(true).Key;

                //is y pressed?
                submitScore = answer == ConsoleKey.Y;
                if (submitScore)
                {
                    var currentScore = ApplicationManager.Instance.Profile.Session.tempScore.Data["Score"];
                    string currentRuleset = ApplicationManager.Instance.Profile.Session.tempScore.Data["Ruleset"];
                    string currentVersion = ApplicationManager.Instance.Profile.Session.tempScore.Data["Version"];
                    string currentSeed = ApplicationManager.Instance.Profile.Session.tempScore.Data["Seed"];

                    try
                    {
                        hs.SubmitScore(guid, name, Convert.ToInt32(currentScore), currentRuleset, currentVersion,Convert.ToInt32(currentSeed));
                    }
                    catch
                    {
                        //HACK: culture string
                        PanelList[0].Clear();
                        PanelList[0].Write("Service unavailable.");
                        WaitKey();
                    }
                }
        }
		

		void Draw()
		{
			Clear();
			PanelList[0].Draw();
		}
	}
}
